package com.example.mobile2030606148tdh0518;

import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
//使用OKHttp进行编程
    //1.定义子线程，定义url链接
    //2.OKHttp对象
    //3.定义请求Requet
    //4.定义call，由okHTTP根据Request生成
    //5.调用execute()执行，获取Response
    //6.调用runOnUiThread()方法，将数据赋值给控件
    private TextView tvMaintitle;
    private TextView tvMainContent;
    //2.定义okhttp对象
    String url="http://192.168.29.230:3000/profile";
    OkHttpClient okHttpClient=new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //匿名对象{]类体
        //new Runnable();
        //接口-实现类-没名称-匿名内部类-匿名对象
        //new Runnable(){}
        //
        initView();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request=new Request.Builder()
                        .url(url)
                        .build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response response=call.execute();
                    String result=response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvMainContent.setText(result);
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }).start();
    }

    private void initView() {
        tvMaintitle = (TextView) findViewById(R.id.tvMaintitle);
        tvMainContent = (TextView) findViewById(R.id.tvMainContent);
    }
}